package com.qf.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.blog.commons.constants.SysConsts;
import com.qf.blog.commons.exception.BusinessException;
import com.qf.blog.commons.security.UserTokenThreadLocal;
import com.qf.blog.dto.FollowCount;
import com.qf.blog.entity.User;
import com.qf.blog.enums.ExceptionEnum;
import com.qf.blog.service.FollowVoService;
import com.qf.blog.service.IUserService;
import com.qf.blog.vo.UserToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
@Slf4j
public class FollowVoServiceImpl implements FollowVoService {
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    IUserService iUserService;

    @Override
    public void follow(Integer followId, Integer type) {
        UserToken userToken = UserTokenThreadLocal.get();
        if (userToken == null) {
            throw new BusinessException(ExceptionEnum.NOT_LOGIN);
        }
        Integer userId = userToken.getUserId();
        ZSetOperations<String, String> zset = redisTemplate.opsForZSet();
        // 登录用户：--》UserId
        // 被关注用户--》FollowId
        String followingKey = String.format(SysConsts.RedisKeys.USER_FOLLOWING_KEY, userId);
        String followerKey = String.format(SysConsts.RedisKeys.USER_FOLLOWER_KEY, followId);

        if (type == 1) {
            // 关注
            zset.add(followingKey, followId.toString(), System.currentTimeMillis());
            zset.add(followerKey, userId.toString(), System.currentTimeMillis());
        } else {
            // 取消关注
            zset.remove(followingKey, followId.toString());
            zset.remove(followerKey, userId.toString());
        }
    }

    @Override
    public boolean isFollow(Integer followId) {
        UserToken userToken = UserTokenThreadLocal.get();
        if (userToken == null) {
            throw new BusinessException(ExceptionEnum.NOT_LOGIN);
        }
        Integer loginUserId = userToken.getUserId();
        ZSetOperations<String, String> zset = redisTemplate.opsForZSet();
        // 登录用户：--》UserId
        // 被关注用户--》FollowId
        String followingKey = String.format(SysConsts.RedisKeys.USER_FOLLOWING_KEY, loginUserId);
        // 判断是否已经关注了，如果没有关注是没有分数的
        Double score = zset.score(followingKey, followId.toString());
        if (score != null) {
            // 关注
            return true;
        } else {
            // 未关注
            return false;
        }
    }

    @Override
    public FollowCount followCount(Integer userId) {
        String followingKey = String.format(SysConsts.RedisKeys.USER_FOLLOWING_KEY, userId);
        String followerKey = String.format(SysConsts.RedisKeys.USER_FOLLOWER_KEY, userId);
        ZSetOperations<String, String> zset = redisTemplate.opsForZSet();
        Long followingCount = zset.zCard(followingKey);
        Long followerCount = zset.zCard(followerKey);
        FollowCount followCount=new FollowCount();
        followCount.setFollowing(followingCount);
        followCount.setFollower(followerCount);
        return followCount;
    }

    @Override
    public List<User> getFollowing(Integer userId) {
        return getFollow(SysConsts.RedisKeys.USER_FOLLOWING_KEY, userId);
    }
    @Override
    public List<User> getFollower(Integer userId) {
        return getFollow(SysConsts.RedisKeys.USER_FOLLOWER_KEY, userId);
    }
    public List<User> getFollow(String key, Integer userId) {
        String followingKey=String.format(key, userId);
        ZSetOperations<String, String> zset=redisTemplate.opsForZSet();
        Set<String> followings=zset.range(followingKey, 0, -1);
        if (followings.size()==0) {
            return new ArrayList<>();
        }
        List<Integer> idList=new ArrayList<>();
        for (String following : followings) {
            Integer followingId=Integer.valueOf(following);
            idList.add(followingId);
        }
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.in("id",idList);
        return iUserService.list(queryWrapper);

    }
}
